package com.stylefeng.guns.modular.system.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.stylefeng.guns.common.constant.Const;
import com.stylefeng.guns.common.persistence.dao.*;
import com.stylefeng.guns.common.persistence.model.*;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.log.LogObjectHolder;
import com.stylefeng.guns.core.page.PageInfoBT;
import com.stylefeng.guns.core.shiro.ShiroKit;
import com.stylefeng.guns.core.util.DateUtil;
import com.stylefeng.guns.core.util.StringUtils;
import com.stylefeng.guns.modular.system.service.ITMonthbalanceDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

/**
 * 账单控制器
 *
 * @author fengshuonan
 * @Date 2018-03-16 10:40:07
 */
@Controller
@RequestMapping("/tMonthbalanceDetail")
public class TMonthbalanceDetailController extends BaseController {

    private String PREFIX = "/system/tMonthbalanceDetail/";

    @Autowired
    private ITMonthbalanceDetailService tMonthbalanceDetailService;

    @Autowired
    private TMonthbalanceDetailMapper monthbalanceDetailMapper;

    @Autowired
    private TBillMapper billMapper;

    @Autowired
    private TMonthbalanceMapper monthbalanceMapper;

    @Autowired
    private TOrderMapper tOrderMapper;

    @Autowired
    private TTrainMapper tTrainMapper;

    @Autowired
    private DictMapper tDictMapper;

    @Autowired
    private UserMapper userMapper;
    /**
     * 跳转到账单首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "tMonthbalanceDetail.html";
    }


    @RequestMapping("/tMonthbalanceDetailList")
    public String tMonthbalanceDetailList(String flag,String id,String bId, Model model) {
        model.addAttribute("flag",flag);//来源 1，收货，2，自提，3，配送，4，中转，5，改单 6 抹平 7 转结 8 新转结
        model.addAttribute("id",id);//monbaldeta_id
        TMonthbalanceDetail tMonthbalanceDetail=monthbalanceDetailMapper.selectById(id);

        User user =userMapper.selectById(tMonthbalanceDetail.getCreater());//用户信息
        switch (flag){
            case "1"://跳转收货详情页
                TTrain tTrain =tTrainMapper.selectById(tMonthbalanceDetail.getIncomeId());//送货情况此处字段为 train_id
                model.addAttribute("tMonthbalanceDetail",tMonthbalanceDetail);
                model.addAttribute("tTrain",tTrain);
                model.addAttribute("tTrainType","送货");
                model.addAttribute("user",user);
                return PREFIX + "tMonthbalanceDetailList.html";
            case "2":
                TOrder tOrder=tOrderMapper.selectById(tMonthbalanceDetail.getIncomeId());
                EntityWrapper< TTrain> entityWrapper=new EntityWrapper<>();
                entityWrapper.where("train_no={0}",tOrder.getBatchNo());
                List<TTrain> list=tTrainMapper.selectList(entityWrapper);
                model.addAttribute("tMonthbalanceDetail",tMonthbalanceDetail);
                model.addAttribute("tTrain",list.get(0));
                model.addAttribute("tTrainType","自提");
                model.addAttribute("user",user);
                return PREFIX + "tMonthbalanceDetailList_ZT.html";
            case "3":
                TTrain tTrain3 =tTrainMapper.selectById(tMonthbalanceDetail.getIncomeId());//送货情况此处字段为 train_id
                model.addAttribute("tMonthbalanceDetail",tMonthbalanceDetail);
                model.addAttribute("tTrain",tTrain3);
                model.addAttribute("tTrainType","配送");
                model.addAttribute("user",user);
                return PREFIX + "tMonthbalanceDetailList_PS.html";
            case "4":
                TTrain tTrain4 =tTrainMapper.selectById(tMonthbalanceDetail.getIncomeId());//送货情况此处字段为 train_id
                model.addAttribute("tMonthbalanceDetail",tMonthbalanceDetail);
                model.addAttribute("tTrain",tTrain4);
                model.addAttribute("tTrainType","中转");
                model.addAttribute("user",user);
                return PREFIX + "tMonthbalanceDetailList_ZZ.html";
//            case "5":
//                break;
//            case "6":
//                break;
//            case "7":
//                break;
            case "8":
                TOrder torder =tOrderMapper.selectById(tMonthbalanceDetail.getIncomeId());
                EntityWrapper< TTrain> entityWrapper1=new EntityWrapper<>();
                entityWrapper1.where("train_no={0}",torder.getBatchNo());
                List<TTrain> tTrains=tTrainMapper.selectList(entityWrapper1);
                TTrain tTrain5=tTrains.get(0);
                model.addAttribute("tMonthbalanceDetail",tMonthbalanceDetail);
                model.addAttribute("tTrain",tTrain5);
                model.addAttribute("tTrainType","新转结");
                model.addAttribute("user",user);
                return PREFIX + "tMonthbalanceDetailList_XZJ.html";
        }


//        try{
//            Integer bIds=Integer.valueOf(bId);
//        }catch (Exception e){
//            bId="0";
//        }
//
//        model.addAttribute("bId",bId);
//
//
//        if(flag.equals("6")||flag.equals("7")||flag.equals("8")){
//            TMonthbalance tMonthbalance= monthbalanceMapper.selectById(Integer.valueOf(bId));
//            model.addAttribute("userName",userMapper.selectById(tMonthbalance.getCreater()).getName());
//            model.addAttribute("tMonthbalance",tMonthbalance);
//            model.addAttribute("dateTime",DateUtil.formatDate(tMonthbalance.getCreatetime(),""));
//            return PREFIX + "tMonthbalanceDetailOtherList.html";
//        }else{
//            EntityWrapper< TOrderFee> entityWrapper=new EntityWrapper<>();
//            entityWrapper.where("balance_id={0}",id);
//            List<TOrderFee> tOrderFees=orderFeeWarpper.selectList(entityWrapper);
//            model.addAttribute("dotName","");
//            if(tOrderFees!=null&&tOrderFees.size()>0){
//                TOrder tOrder=tOrderMapper.selectById(tOrderFees.get(0).getOrderId());
//                model.addAttribute("dotName",dotMapper.selectById(tOrder.getDotId()).getDotName());
//                model.addAttribute("tOrder",tOrder);
////                if(tOrder.getIsTransfer().equals("1")){
////                    model.addAttribute("flag","4");//中转单
////                }else{
////                    if(tOrder.getMode()==0){
////                        model.addAttribute("flag","2");//自提
////                    }else{
////                        model.addAttribute("flag","3");
////                    }
////                }
//                TTrain tTrain1=tTrainMapper.selectById(tOrder.getBacth_id());
//                model.addAttribute("tTrain1",tTrain1);
//                if(tOrder.getTrain_id()!=null){
//                    TTrain tTrain2=tTrainMapper.selectById(tOrder.getTrain_id());
//                    model.addAttribute("tTrain2",tTrain2);
//                }else{
//                    model.addAttribute("tTrain2",new TTrain());
//                }
//            }else{
//                model.addAttribute("tOrder",new TOrder());
//                model.addAttribute("tTrain1",new TTrain());
//                model.addAttribute("tTrain2",new TTrain());
//            }
//            TMonthbalanceDetail tMonthbalanceDetail= monthbalanceDetailMapper.selectById(Integer.valueOf(id));
//            model.addAttribute("tMonthbalanceDetail",tMonthbalanceDetail);
//            model.addAttribute("userName",userMapper.selectById(tMonthbalanceDetail.getCreater()).getName());
//            model.addAttribute("dateTime",DateUtil.formatDate(tMonthbalanceDetail.getCreatetime(),""));
//        }
        return PREFIX + "tMonthbalanceDetailList.html";
    }

    /**
     * 月结账单核算
     */
    @RequestMapping("/tMonthbalanceDetail_update")
    public String tMonthbalanceDetailUpdate( Model model,String ids,String name) {
        model.addAttribute("ids",ids);
        model.addAttribute("name",name);
        return PREFIX + "tMonthbalanceDetail_edit.html";
    }


    @RequestMapping("/tMonthbalanceDetailOtherUpdate/{tMonthbalanceDetailId}")
    public String tMonthbalanceDetailOtherUpdate(@PathVariable Integer tMonthbalanceDetailId, Model model,String ids,String name,String bId) {
        TMonthbalanceDetail tMonthbalanceDetail = tMonthbalanceDetailService.selectById(tMonthbalanceDetailId);
        model.addAttribute("ids",ids);
        model.addAttribute("name",name);
        model.addAttribute("bId",bId);
        model.addAttribute("item",tMonthbalanceDetail);
        LogObjectHolder.me().set(tMonthbalanceDetail);
        return PREFIX + "tMonthbalanceDetailOther_edit.html";
    }

    /**
     * 获取账单列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(Integer limit, Integer offset) {
        Page<Map<String, Object>> page = new Page(offset, limit);
        PageInfoBT pageInfoBT = new PageInfoBT(page);
        String dot_id = ShiroKit.getUser().getDotId() + "";
        String name=getPara("name");
        String beginTime=getPara("beginTime");
        String endTime=getPara("endTime");
        String status=getPara("status");
        if(StringUtils.isEmpty(status)){
            status="0";
        }
        Map param=new HashMap();
        param.put("dot_id",dot_id);
        param.put("name",name);
        param.put("beginTime",beginTime);
        param.put("endTime",endTime);
        param.put("status",status);
        List<Map<String, Object>> dots = monthbalanceDetailMapper.monthList(page, param);
        pageInfoBT.setData(dots);
        pageInfoBT.setCount(page.getTotal());
        return pageInfoBT;
    }

    @RequestMapping(value = "/listGroup")
    @ResponseBody
    public Object listGroup() {
        String dot_id = ShiroKit.getUser().getDotId() + "";
        String name=getPara("name");
        String beginTime=getPara("beginTime");
        String endTime=getPara("endTime");
        String status=getPara("status");
        if(StringUtils.isEmpty(status)){
            status="0";
        }
        Map param=new HashMap();
        param.put("dot_id",dot_id);
        param.put("name",name);
        param.put("beginTime",beginTime);
        param.put("endTime",endTime);
        param.put("status",status);
        Map<String, Object> dots = monthbalanceDetailMapper.monthGroup(param);
        return dots;
    }


    @RequestMapping(value = "/listDetail")
    @ResponseBody
    public Object listDetail(@RequestParam(required = false) String flag,String id,Integer limit, Integer offset) {
        Page<Map<String, Object>> page = new Page(0, 1000);
        PageInfoBT pageInfoBT = new PageInfoBT(page);
        List<Map<String, Object>> dots = null;
        if(flag.equals("1")){//上游
            dots=monthbalanceDetailMapper.monthDetailListSS(page,id);
        }else if(flag.equals("2")){//自提
            dots=monthbalanceDetailMapper.monthDetailListZT(page,id);
        }else if(flag.equals("3")){//配送
            dots=monthbalanceDetailMapper.monthDetailListPS(page,id);
        }else if(flag.equals("4")){//中转
            dots=monthbalanceDetailMapper.monthDetailListZZ(page,id);
        }else{//其他
            dots=monthbalanceDetailMapper.monthDetailOtherList(page,id);
        }
        pageInfoBT.setData(dots);
        pageInfoBT.setCount(page.getTotal());
        return pageInfoBT;
    }

    @RequestMapping(value = "/listDetailZJ")
    @ResponseBody
    public Object listDetailZJ(@RequestParam(required = false) String bId,String id,
                             Integer limit, Integer offset) {
        Page<Map<String, Object>> page = new Page(0, 1000);
        PageInfoBT pageInfoBT = new PageInfoBT(page);
        List<Map<String, Object>> dots =monthbalanceDetailMapper.monthDetailZJList(page,bId,id);


        pageInfoBT.setData(dots);
        pageInfoBT.setCount(page.getTotal());
        return pageInfoBT;
    }

    @RequestMapping(value = "/settlementList")
    @ResponseBody
    public Object settlementList(@RequestParam(required = false) String ids,Integer limit, Integer offset) {
        List<Integer> list=new ArrayList<>();
        String strId[]=ids.split(",");
        for(int i=0;i<strId.length;i++){
            list.add(Integer.valueOf(strId[i]));
        }
        Page<Map<String, Object>> page = new Page(0, 1000);
        PageInfoBT pageInfoBT = new PageInfoBT(page);
        List<Map<String, Object>> dots = monthbalanceDetailMapper.monthDetailList(page, list);
        pageInfoBT.setData(dots);
        pageInfoBT.setCount(page.getTotal());
        return pageInfoBT;
    }

    /**
     * 新增账单
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(TMonthbalanceDetail tMonthbalanceDetail) {
        tMonthbalanceDetailService.insert(tMonthbalanceDetail);
        return super.SUCCESS_TIP;
    }

    /**
     * 删除账单
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam Integer tMonthbalanceDetailId) {
        tMonthbalanceDetailService.deleteById(tMonthbalanceDetailId);
        return SUCCESS_TIP;
    }

    /**
     * 修改账单
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(TMonthbalanceDetail tMonthbalanceDetail,String ids,String cash,String weixin,String alipay,String bank) {

        Map param=new HashMap();
        param.put("dot_id",ShiroKit.getUser().getDotId());
        param.put("nType", Const.NTYPE_04); // 类别 00 初始 01 配送 02 中转 03 自提  04 月结
        String bath_no = tDictMapper.getNumCode(param);
        String billNum= "TT"+ShiroKit.getUser().getId()+"_"+ DateUtil.getAllTimes();
        String traner=getPara("traner");
        String hj=getPara("hj");//合计金额，实际应付金额
//        String m1=getPara("m1");
//        String m2=getPara("m2");
        String strId[]=ids.split(",");

        TBill bill=new TBill();
        bill.setWeixin(Float.valueOf(weixin));
        bill.setAlipay(Float.valueOf(alipay));
        bill.setCash(Float.valueOf(cash));
        bill.setBillNum(billNum);
        bill.setBank(Float.valueOf(bank));
        bill.setDotId(ShiroKit.getUser().getDotId());
        bill.setCreateTime(new Date());
        bill.setEditUser(ShiroKit.getUser().getId());
        billMapper.insert(bill);

        //插入月账单
        TMonthbalance monthbalance=new TMonthbalance();
        monthbalance.setBatchCount(strId.length);
        monthbalance.setBillId(bill.getId());
        monthbalance.setDotId(ShiroKit.getUser().getDotId());
        monthbalance.setCreater(ShiroKit.getUser().getId());
        monthbalance.setCreatetime(new Date());
        monthbalance.setTraner(traner);
        if(tMonthbalanceDetail.getIncome()==6){//抹平
            monthbalance.setMoneyActual(Double.valueOf(weixin)+Double.valueOf(alipay)
                    +Double.valueOf(cash)+Double.valueOf(bank));
            monthbalance.setMoneyShould(Double.valueOf(hj));
            monthbalance.setBalanceType(2);
            monthbalanceMapper.insert(monthbalance);
        }else if(tMonthbalanceDetail.getIncome()==7){//转结
            monthbalance.setMoneyActual(Double.valueOf(weixin)+Double.valueOf(alipay)
                    +Double.valueOf(cash)+Double.valueOf(bank));
            monthbalance.setMoneyShould(Double.valueOf(hj));
            monthbalance.setBalanceType(1);
            monthbalanceMapper.insert(monthbalance);
        }else{//正常
            monthbalance.setBalanceType(0);
            monthbalance.setMoneyActual(Double.valueOf(weixin)+Double.valueOf(alipay)
                    +Double.valueOf(cash)+Double.valueOf(bank));
            monthbalance.setMoneyShould(Double.valueOf(hj));
            monthbalanceMapper.insert(monthbalance);
        }



        //先更新账单的状态
        for(int i=0;i<strId.length;i++){
            TMonthbalanceDetail as=new TMonthbalanceDetail();
            as.setId(Integer.valueOf(strId[i]));
            as.setStatus("1");
//            as.setIncome(tMonthbalanceDetail.getIncome());
            as.setBillId(bill.getId());
            as.setMonthbalanceId(monthbalance.getId());
            tMonthbalanceDetailService.updateById(as);

        }
        if(tMonthbalanceDetail.getIncome()==6){//抹平
            //生成新的账单记录表并插入monthbalance_id



            TMonthbalanceDetail sMonthbalanceDetail=new TMonthbalanceDetail();
            sMonthbalanceDetail.setCreater(ShiroKit.getUser().getId());
            sMonthbalanceDetail.setCreatetime(new Date());
            sMonthbalanceDetail.setDotId(ShiroKit.getUser().getDotId());
            sMonthbalanceDetail.setIncome(6);
            sMonthbalanceDetail.setStatus("1");
            sMonthbalanceDetail.setSettlementType(1);//1 月结
            sMonthbalanceDetail.setMoney((Double.valueOf(hj)-(Double.valueOf(weixin)+Double.valueOf(alipay)
                    +Double.valueOf(cash)+Double.valueOf(bank)))*(-1));
            sMonthbalanceDetail.setRemark(tMonthbalanceDetail.getRemark());
            sMonthbalanceDetail.setTraner(traner);
            sMonthbalanceDetail.setBillId(bill.getId());
            sMonthbalanceDetail.setMonthbalanceId(monthbalance.getId());
//            sMonthbalanceDetail.setBalance_num("XJ"+ ShiroKit.getUser().getId()+"_"+ DateUtil.getAllTimes());
            sMonthbalanceDetail.setBalance_num(bath_no);
            tMonthbalanceDetailService.insert(sMonthbalanceDetail);
            //将id 回填到 balance monthbalance__detail_id
            TMonthbalance mb=new TMonthbalance();
            mb.setId(monthbalance.getId());
            mb.setMonthbalanceDetailId(sMonthbalanceDetail.getId());
            monthbalanceMapper.updateById(mb);
        }else  if(tMonthbalanceDetail.getIncome()==7){//转结
            TMonthbalanceDetail sMonthbalanceDetail1=new TMonthbalanceDetail();
            sMonthbalanceDetail1.setCreater(ShiroKit.getUser().getId());
            sMonthbalanceDetail1.setCreatetime(new Date());
            sMonthbalanceDetail1.setDotId(ShiroKit.getUser().getDotId());
            sMonthbalanceDetail1.setIncome(7);
            sMonthbalanceDetail1.setStatus("1");
            sMonthbalanceDetail1.setSettlementType(1);//1 月结
            sMonthbalanceDetail1.setMoney((Double.valueOf(hj)-(Double.valueOf(weixin)+Double.valueOf(alipay)
                    +Double.valueOf(cash)+Double.valueOf(bank)))*(-1));
            sMonthbalanceDetail1.setRemark(tMonthbalanceDetail.getRemark());
            sMonthbalanceDetail1.setTraner(traner);
            sMonthbalanceDetail1.setMonthbalanceId(monthbalance.getId());
            sMonthbalanceDetail1.setBillId(bill.getId());
//            sMonthbalanceDetail1.setBalance_num("XJ"+ ShiroKit.getUser().getId()+"_"+ DateUtil.getAllTimes());
            sMonthbalanceDetail1.setBalance_num(bath_no);
            tMonthbalanceDetailService.insert(sMonthbalanceDetail1);


                //插入新转结
                TMonthbalanceDetail sMonthbalanceDetail2=new TMonthbalanceDetail();
                sMonthbalanceDetail2.setCreater(ShiroKit.getUser().getId());
                sMonthbalanceDetail2.setCreatetime(new Date());
                sMonthbalanceDetail2.setDotId(ShiroKit.getUser().getDotId());
                sMonthbalanceDetail2.setIncome(8);
                sMonthbalanceDetail2.setSettlementType(1);//1 月结
               //sMonthbalanceDetail2.setIncomeId(monthbalance.getId());
                sMonthbalanceDetail2.setIncomeName(monthbalance.getId()+"");
                sMonthbalanceDetail2.setStatus("0");
                sMonthbalanceDetail2.setMoney( Double.valueOf(hj)-(Double.valueOf(weixin)+Double.valueOf(alipay)
                        +Double.valueOf(cash)+Double.valueOf(bank)));
                sMonthbalanceDetail2.setRemark("");
                sMonthbalanceDetail2.setTraner(traner);
                sMonthbalanceDetail2.setMonthbalanceId(monthbalance.getId());
//                sMonthbalanceDetail2.setBalance_num("XJ"+ ShiroKit.getUser().getId()+"_"+ DateUtil.getAllTimes());
                sMonthbalanceDetail2.setBalance_num(bath_no);
                tMonthbalanceDetailService.insert(sMonthbalanceDetail2);
                //新转结的订单回填 balance表
                TMonthbalance mb=new TMonthbalance();
                mb.setId(monthbalance.getId());
                mb.setMonthbalanceDetailId(sMonthbalanceDetail2.getId());

                monthbalanceMapper.updateById(mb);
        }
        return super.SUCCESS_TIP;
    }

    /**
     * 账单详情
     */
    @RequestMapping(value = "/detail/{tMonthbalanceDetailId}")
    @ResponseBody
    public Object detail(@PathVariable("tMonthbalanceDetailId") Integer tMonthbalanceDetailId) {
        return tMonthbalanceDetailService.selectById(tMonthbalanceDetailId);
    }
}
